package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.anno.Log;
import org.example.pojo.Dept;
import org.example.pojo.Result;
import org.example.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/depts")
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;
//    @RequestMapping(value = "/depts",method = RequestMethod.GET)
    @GetMapping
    public Result list(){
//        System.out.println("查询全部部门数据");
        log.info("查询全部部门数据");
        List<Dept> deptList =deptService.findAll();
        return Result.success(deptList);
    }

//    删除部门
//    注意事项：一旦声明了@RequestParam,该参数在请求时必须传递，如果不传递将会报错，（默认required为true）
    @Log
    @DeleteMapping
    public Result delete(Integer id){
//        System.out.println("根据ID删除部门"+id);
        log.info("根据ID删除部门:{}",id);
        boolean flag =deptService.deleteById(id);
        if(flag)
            return Result.success();
        return Result.error("对不起，当前部门下有员工，不能直接删除！");
    }

//    添加部门
    @Log
    @PostMapping
    public Result add(@RequestBody Dept dept){
//        System.out.println("添加部门"+dept);
        log.info("添加部门:{}",dept);
        deptService.add(dept);
        return Result.success();
    }

//    根据id查询部门
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable Integer id){
//        System.out.println("根据id查询部门:" + id);
        log.info("根据id查询部门:{}",id);
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

//    修改部门
    @Log
    @PutMapping
    public Result update(@RequestBody Dept dept){
//        System.out.println("修改部门:" + dept);
        log.info("修改部门:{}",dept);
        deptService.update(dept);
        return Result.success();
    }
}
